package com.geek.admin.common.domain;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author gaozeyu
 */
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "分页信息",description = "分页信息")
@Data
public class PageVO implements Serializable {
    private static final long serialVersionUID = 1L;
    @ApiModelProperty("当前页码，从1开始")
    private Long current;
    @ApiModelProperty("每页的数据量")
    private Long size;
    @ApiModelProperty("总数据量")
    private Long total;
    @ApiModelProperty("正序排序的字段列表")
    private String[] ascs;
    @ApiModelProperty("倒序排序的字段列表")
    private String[] descs;

    public static <T extends PageVO> void transform(IPage page, T vo) {
        vo.setCurrent(page.getCurrent());
        vo.setSize(page.getSize());
        vo.setTotal(page.getTotal());
        vo.setAscs(ascs(page.orders()));
        vo.setDescs(descs(page.orders()));
    }

    private static String[] ascs(List<OrderItem> orders) {
        return mapOrderToArray(orders, OrderItem::isAsc);
    }

    private static String[] descs(List<OrderItem> orders) {
        return mapOrderToArray(orders, (i) -> {
            return !i.isAsc();
        });
    }

    private static String[] mapOrderToArray(List<OrderItem> orders, Predicate<OrderItem> filter) {
        List<String> columns = new ArrayList(orders.size());
        orders.forEach((i) -> {
            if (filter.test(i)) {
                columns.add(i.getColumn());
            }

        });
        return (String[])columns.toArray(new String[0]);
    }

    public PageVO() {
    }

}
